//
//  MJRefresh+Rx.swift
//  TestSwift
//
//  Created by Song on 2018/9/14.
//  Copyright © 2018年 Song. All rights reserved.
//

import RxSwift
import RxCocoa
import MJRefresh

extension Reactive where Base: MJRefreshComponent {
    /// 正在刷新
    var qs_refreshing: ControlEvent<Void> {
        let source: Observable<Void> = Observable.create {
            [weak control = self.base] observer -> Disposable  in
            MainScheduler.ensureExecutingOnScheduler()
            
            guard let control = control else {
                observer.on(.completed)
                return Disposables.create()
            }
            
            control.refreshingBlock = {
                observer.on(.next(()))
            }
            return Disposables.create()
            }
            .takeUntil(deallocated)
        
        return ControlEvent(events: source)
    }
}

extension Reactive where Base: MJRefreshHeader {
    /// 停止头部刷新
    var qs_endHeaderRefreshing: Binder<Bool> {
        return Binder.init(base) { (header, isEnd) in
            if isEnd {
                header.endRefreshing()
            }
        }
    }
}

extension Reactive where Base: MJRefreshFooter {
    /// 停止尾部刷新 (Bool, Bool)：(是否停止刷新， 是否已经没有更多数据了)
    var qs_endFooterRefreshing: Binder<(Bool, Bool)> {
        return Binder.init(base, binding: { (footer, arg1) in
            let (isEnd, hasNoMore) = arg1
            if isEnd {
                if hasNoMore {
                    footer.endRefreshingWithNoMoreData()
                } else {
                    footer.endRefreshing()
                }
            }
        })
    }
}

extension Reactive where Base: UIScrollView {
    /// 向上滚动，取消上拉
    public var qs_isUpDragging: ControlEvent<Bool> {
        let source = base.rx.didEndDragging
            .map { (_) -> Bool in
                let translation = self.base.panGestureRecognizer.translation(in: self.base.superview)
                
                if translation.y < 0 {
                    return true
                } else {
                    return false
                }
        }
        
        return ControlEvent(events: source)
    }
    
    /// 向下滚动，取消下拉
    public var qs_isDrowDragging: ControlEvent<(Bool, Bool)> {
        let source = base.rx.didEndDragging
            .map { (_) -> (Bool, Bool) in
                let translation = self.base.panGestureRecognizer.translation(in: self.base.superview)
                
                if translation.y > 0 {
                    return (true, false)
                } else {
                    return (false, false)
                }
        }
        
        return ControlEvent(events: source)
    }
}
